<?php
			
	/* SVN FILE: $Id: index.php 8 2011-03-13 08:32:38Z michele.andreoletti@gmail.com $ */
	
	/**
	 * Project Name : arcadia
	 *
	 * @author $Author: michele.andreoletti@gmail.com $
	 * @version $Revision: 8 $
	 * @lastrevision $Date: 2011-03-13 08:32:38 +0000 (Sun, 13 Mar 2011) $
	 * @filesource $URL: http://arcadia.googlecode.com/svn/trunk/sysop/index.php $
	 */

	require_once '../include/functions.php';
	require_once '../include/const.inc.php';
	require_once '../include/auth.inc.php';
	require_once '../include/conn.inc.php';

	fnOnly4Sysop();

	$sScript = fnCurrentScript();
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php
	
	fnGetValueFromGET(array('sType'));
	if (!isset($sType)) $sType='user'; // se eseguo lo script senza passare il parametro sType, viene impostato di default == 'user'
	
	switch ($sType) {

		case "group":
			$sLabel = "Gruppi";
			$aColumns = array('sUsername','sDisplayname');
			$sColumnDefs = "{ 'sWidth': '20px', 'sClass': 'center', 'aTargets': [ -1 ] }";
			$aFlag = array();		
			break;
	
		default:
			$sType = 'user';
			$sLabel = "Utenti";
			$aColumns = array('sUsername','iEnabled','sDisplayname','sEmail','iSysop');
			$sColumnDefs = "{ 'sWidth': '20px', 'sClass': 'center', 'aTargets': [ 1, -2, -1 ] }";
			$aFlag = array('iEnabled','iSysop');
			break;

	}
			
	$sAPP_NAME = '&nbsp;';
	$sLEFT_NAV_IMG = "config-users.png";
	$sHeaderTitle = $sTableTitle = "$sSUITE_NAME &raquo; Gestione $sLabel";
	
	$sNewItem = "<a href='#' id='new-".$sType."'>Crea un nuovo utente &raquo;</a>";
	
	$sHeadContent = "
		<script type='text/javascript' src='".$sSCRIPT_ROOT_PATH."/include/dataTables/media/js/jquery.dataTables.js'></script>
		<link type='text/css' href='".$sSCRIPT_ROOT_PATH."/include/dataTables/media/css/demo_table.css' rel='stylesheet' />

		<script type='text/javascript' src='./include/user.js'></script>

		<script type='text/javascript' charset='utf-8'>

			var oTable;
			var oClicked;
			
			function HoverImgOf(filename) {
			   var re = new RegExp('(.+)\\.(gif|png|jpg)', 'g');
			   return filename.replace(re, '$1_f2.$2'); }
			function NormalImgOf(filename) {
			   var re = new RegExp('(.+)_f2\\.(gif|png|jpg)', 'g');
			   return filename.replace(re, '$1.$2'); }
			
			function fnTrashUsername(sUsername, sType) {
				$.getJSON('actions.php', { 'sUsername': sUsername, 'sType': sType, 'sAction': 'trash' }, function(json) {
					var anSelected = fnGetSelected(oTable);
					oTable.fnDeleteRow(anSelected[0]);
				});
			};

			function fnRemoveSelected(oObj){
				$(oObj.fnSettings().aoData).each(function() {
					$(this.nTr).removeClass('row_selected');
				});
			}

			/* Get the rows which are currently selected */
			function fnGetSelected(oTableLocal) {
				var aReturn = new Array();
				var aTrs = oTableLocal.fnGetNodes();
				for (var i=0; i<aTrs.length; i++) {
					if ($(aTrs[i]).hasClass('row_selected')) {
						aReturn.push(aTrs[i]);
					}
				}
				return aReturn;
			}
							
			function fnCreateUser(oUser, oDescription, oEmail, oPass) {
				$.getJSON('actions.php', { 'sUsername': oUser.val(), 'sAction': 'create', 'sType': 'user', 'sDisplayname': oDescription.val(), 'sEmail': oEmail.val(), 'sPassword': oPass.val() });
			};
			
			function fnCreateGroup(oUser, oDescription) {
				$.getJSON('actions.php', { 'sUsername': oUser.val(), 'sAction': 'create', 'sType': 'group',  'sDisplayname': oDescription.val() });
			};
									


			$(document).ready(function() {
	
				oUsername = $('#sUsername'),
					oDisplayname = $('#sDisplayname'),
					oEmail = $('#sEmail'),
					oPassword = $('#sPassword'),
					oAllFields = $([]).add(oUsername).add(oDisplayname).add(oEmail).add(oPassword),
					oTips = $('.validateTips');
									
				oGroupname = $('#sGroupname'),
					oDescription = $('#sDescription'),
					oAllFieldsG = $([]).add(oGroupname).add(oDescription);
					
				$('.trash-trigger').hover( function() {
						var hoverImg = HoverImgOf($(this).attr('src'));
						$(this).attr('src', hoverImg);
					}, function() {
						var normalImg = NormalImgOf($(this).attr('src'));
						$(this).attr('src', normalImg);
					}
				).click(function() {
					$(oTable.fnSettings().aoData).each(function() {
						$(this.nTr).removeClass('row_selected');
					});
					oClicked = $(this);
					oClicked.parents('tr:first').addClass('row_selected');
					$('#trash-username-dialog .text').text($(this).attr('sUsername'));
					$('#trash-username-dialog').dialog('open');
					return false;
				});
						
				$('#trash-username-dialog').dialog({
					autoOpen: false,
				  	resizable: false,
					modal: true,
					buttons: {
						'Elimina': function() {
							fnTrashUsername(oClicked.attr('sUsername'), '$sType');
							$(this).dialog('close');
						},
						Annulla: function() {
							fnRemoveSelected(oTable);
							$(this).dialog('close');
						}
					},
					close: function() {
						fnRemoveSelected(oTable);
					}
				});
				
				$('#new-user').click(function() {
					$('#new-user-dialog').dialog('open');
				});

				$('#new-user-dialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Crea Utente': function() {
							var bValid = true;
							oAllFields.removeClass('ui-state-error');
							
							bValid = bValid && checkLength(oUsername,'Username',4,32);
							bValid = bValid && checkUsername(oUsername);
							bValid = bValid && checkRegexp(oUsername,/^[a-z]([0-9a-z_])+$/i,'Username può contenere i caratteri a-z, 0-9, underscore, e deve cominciare con una lettera.');
							
							bValid = bValid && checkLength(oDisplayname,'Descrizione',4,96);
							
							bValid = bValid && checkLength(oEmail,'Email',6,96);
							
							bValid = bValid && checkLength(oPassword,'Password',5,16);
							bValid = bValid && checkRegexp(oPassword,/^([0-9a-zA-Z])+$/,'La Password può contenere solo i seguenti caratteri: a-z, 0-9.');
							
							if (bValid) {
								fnCreateUser(oUsername, oDisplayname, oEmail, oPassword);
								oTable.fnAddData( [
									\"<a href='edit.php?sUsername=\" + oUsername.val() + \"&sType=user' class='unique user'>\" + oUsername.val() + '</a>',
									\"<img src='../themes/common/images/icon_check.png'>\",
									oDisplayname.val(),
									oEmail.val(),
									\"<img src='../themes/common/images/empty.png'>\",
									'&nbsp;' ] );
								$(this).dialog('close');
							}
						},
						Annulla: function() {
							$(this).dialog('close');
						}
					},
					close: function() {
						oAllFields.val('').removeClass('ui-state-error');
					}
				});
				
				$('#new-group').click(function() {
					$('#new-group-dialog').dialog('open');
				});

				$('#new-group-dialog').dialog({
					autoOpen: false,
					resizable: false,
					modal: true,
					buttons: {
						'Crea Gruppo': function() {
							var bValid = true;
							oAllFieldsG.removeClass('ui-state-error');
							
							bValid = bValid && checkLength(oGroupname,'Nome Gruppo',4,32);
							bValid = bValid && checkUsername(oGroupname);
							bValid = bValid && checkRegexp(oGroupname,/^[a-z]([0-9a-z_])+$/i,'il Nome del Gruppo può contenere i caratteri a-z, 0-9, underscore, e deve cominciare con una lettera.');
							
							bValid = bValid && checkLength(oDescription,'Descrizione',4,96);
		
						if (bValid) {
								fnCreateGroup(oGroupname, oDescription);
								oTable.fnAddData( [
									\"<a href='edit.php?sUsername=\" + oGroupname.val() + \"&sType=group' class='unique group'>\" + oGroupname.val() + '</a>',
									oDescription.val(),
									'&nbsp;' ] );
								$(this).dialog('close');
							}
						},
						Annulla: function() {
							$(this).dialog('close');
						}
					},
					close: function() {
						oAllFieldsG.val('').removeClass('ui-state-error');
					}
				});
				/* Init DataTables */
				oTable = $('.security-table').dataTable({
					'bPaginate': false,
					'bLengthChange': false,
					'bFilter': false,
					'bSort': false,
					'bInfo': false,
					'aoColumnDefs': [ $sColumnDefs ]
				});
		
			});

		</script> ";
	
	$html .= "<br/>";
		
	$html .= fnHtmlUserManagerTable($sType, $aColumns, $aFlag);
		
	$html .= "
		<div class='dialog' id='trash-username-dialog' title='Elimina'>
			<p>Sei sicuro di voler eliminare <strong><span class='text'></span></strong>?</p>
			<p>Questa operazione non potrà essere annullata.</p>
		</div>";
	
	$html .= "	
		<div class='dialog' id='new-user-dialog' title='Nuovo Utente'>
			<p class='validateTips'>Tutti i campi sono obbligatori.</p>
			<form>
				<fieldset>
					<label for='sUsername'>Username</label>
					<input type='text' name='sUsername' id='sUsername' class='text ui-widget-content ui-corner-all' />
					<label for='sDisplayname'>Descrizione</label>
					<input type='text' name='sDisplayname' id='sDisplayname' value='' class='text ui-widget-content ui-corner-all' />
					<label for='sEmail'>Email</label>
					<input type='text' name='sEmail' id='sEmail' value='' class='text ui-widget-content ui-corner-all' />
					<label for='sPassword'>Password</label>
					<input type='password' name='sPassword' id='sPassword' value='' class='text ui-widget-content ui-corner-all' />
				</fieldset>
			</form>
		</div>";

	$html .= "	
		<div class='dialog' id='new-group-dialog' title='Nuovo Gruppo'>
			<p class='validateTips'>Tutti i campi sono obbligatori.</p>
			<form>
				<fieldset>
					<label for='sGroupname'>Nome Gruppo</label>
					<input type='text' name='sGroupname' id='sGroupname' class='text ui-widget-content ui-corner-all' />
					<label for='sDescription'>Descrizione</label>
					<input type='text' name='sDescription' id='sDescription' value='' class='text ui-widget-content ui-corner-all' />
				</fieldset>
			</form>
		</div>";
		
	require_once('../themes/'.$sTHEME.'/template.php');
	die();

?><html><body bgcolor="#fff"></body></html>



<?php

	function fnHtmlUserManagerTable ($sType, $aColumns, $aFlag) {
		
		$aData = fnGetDataFromQuery(fnQueryUsers($sType), 'fnHtmlUserManagerTable()');
		
		$html = "<table class='security-table display' cellspacing='0' cellpadding='0'>";
		$html .= "	<thead>
						<tr>";
		foreach ($aColumns as $sColumn) {
			$html .= "		<th>".(in_array($sColumn, $aFlag) ? $sColumn :  "&nbsp;")."</th>";
		}
		$html .= "			<th>&nbsp;</th>";
		$html .= "		</tr>
					</thead>";
		$html .= "	<tbody>";			
		foreach ($aData as $aRow) {
			$html .= "	<tr>";
			foreach ($aColumns as $sColumn) {
				if ($sColumn == 'sUsername') {
						$sContent = "<a href='edit.php?sUsername=".$aRow['sUsername']."&sType=$sType' class='".$sType.($aRow['iEnabled']==0 ? " disabled " : '')." unique'>".$aRow[$sColumn]."</a>";	
				} else if (in_array($sColumn, $aFlag)) {
					$sContent = "<img src='../themes/common/images/".($aRow[$sColumn]==1 ? "icon_check" : "empty").".png'>";
				} else {
					$sContent = $aRow[$sColumn];	
				}
				$html .= "	<td>$sContent</td>";
			}
			$html .= "		<td><img sUsername='".$aRow['sUsername']."' class='trash-trigger' src='../themes/common/images/icn_trash.gif'></td>";
			$html .= "	</tr>";		
		}
		$html .= "	</tbody>";
		$html .= "</table>";
		
		return $html;
	}	

?>